<?php

include dirname(__FILE__) . '/../../class/_core.php';
include dirname(__FILE__) . '/../../class/department.php';

$department = new department();
$view = $department->department_view_all();

$from = $_GET['from'];
$to = $_GET['to'];
$code = $_GET['pdcode'];
$month = date('Y-m');

if ($from != "" && $to != "") {
    $twhereA = "AND fd1.create_time>='$from' AND fd1.create_time<='$to'";
    $twhereB = "AND fd2.create_time>='$from' AND fd2.create_time<='$to'";
}
if ($code != "") {
    $twhere1 = "AND order_id = '$code' ";
}

foreach ($view as &$v) {
    $v['produce'] = array();
    $departmentId = intval($v['department_id']);
    $orderIds = Db::get_instance()->query("select order_id FROM fac_department_receive_record where department_id = $departmentId $twhere1 UNION select order_id FROM fac_department_product_record where department_id = $departmentId $twhere1;");
    foreach ($orderIds as $orderId) {
        $orderId = intval($orderId['order_id']);
        $ret = Db::get_instance()->query("SELECT
	(
		SELECT
			SUM(fd1.number)
		FROM
			fac_department_product_record fd1
		WHERE
			fd1.department_id = $departmentId
		AND fd1.order_id = $orderId $twhereA
	) AS numberX,
	(
		SELECT
			SUM(fd2.number)
		FROM
			fac_department_receive_record fd2
		WHERE
			fd2.department_id = $departmentId
		AND fd2.order_id = $orderId $twhereB
	) AS getX,
	product_order_code,
	product_model,
	product_code,
	gongyi
FROM
	fac_product_order
LEFT JOIN fac_product_mess fm ON fac_product_order.product_id = fm.product_id
WHERE
	fac_product_order.product_order_id = $orderId;");
        foreach ($ret AS &$p) {
            if ($p['getX'] == 0 || $p['numberX'] == 0) {
                $p['rate'] = false;
            } else {
                $p['rate'] = round(($p['numberX'] / $p['getX']) * 100, 2);
            }
        }
        $v['produce'] = array_merge($v['produce'],$ret);
    }
}

// 获取生产编号
$pCode = Db::get_instance()->query("SELECT product_order_id,product_order_code FROM fac_product_order");

$Smarty->assign('cd', $code);
$Smarty->assign('pCode', $pCode);
$Smarty->assign('from', $from);
$Smarty->assign('to', $to);
$Smarty->assign('dept', $view);
$Smarty->display('department/department_status.tpl');
